package Sort;

import java.util.Arrays;

/**
 * @Author Fizz Pu
 * @Date 2021/4/2 下午4:18
 * @Version 1.0
 * 失之毫厘，缪之千里！
 */

public class MergeSort implements SortAlgrithom{
    @Override
    public void sort(int[] arr) {
        sortArray(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }

    private void sortArray(int[] arr, int left, int right){
        if(left < right) {
            int mid = (left + right) / 2;
            sortArray(arr, left, mid);
            sortArray(arr, mid + 1, right);
            mergeArray(arr, left, mid, right);
        }
    }

    // left -> mid 有序序列
    // mid + 1 -> right 有序序列
    private void mergeArray(int[] arr, int left, int mid, int right){
        int i = left;
        int j = mid + 1;
        int [] tempArray = new int[right-left + 1];
        int tempArrayIndex = 0;
        while(i <= mid && j <= right){
            if(arr[i] < arr[j]){
                tempArray[tempArrayIndex++] = arr[i++];
                continue;
            }

            if(arr[j] < arr[i]){
                tempArray[tempArrayIndex++] = arr[j++];
                continue;
            }

            if(arr[j] == arr[i]){
                tempArray[tempArrayIndex++] = arr[j++];
                tempArray[tempArrayIndex++] = arr[i++];
                continue;
            }
        }

        while(i <= mid){
            tempArray[tempArrayIndex++] = arr[i++];
        }

        while (j <= right){
            tempArray[tempArrayIndex++] = arr[j++];
        }

        // 复制回去
        tempArrayIndex = 0;
        for(int t = left; t <= right; t++){
            arr[t] = tempArray[tempArrayIndex++];
        }

        tempArray = null;
    }
}
